<template>
  <!-- 新增子账号 表单 -->
  <a-modal
    v-model:open="visible"
    title="新增子账号"
    class="addStation"
    destroyOnClose
    :width="520"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
    >
      <a-form-item label="子账号" name="account">
        <a-input
          v-model:value="form.account"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="子账号名称" name="username">
        <a-input
          v-model:value="form.username"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item has-feedback label="子账号密码" name="password">
        <a-input
          v-model:value="form.password"
          type="password"
          autocomplete="off"
          class="formInput"
        />
      </a-form-item>
      <a-form-item has-feedback label="确认密码" name="checkPassWord">
        <a-input
          v-model:value="form.checkPassWord"
          type="password"
          autocomplete="off"
          class="formInput"
        />
      </a-form-item>
      <a-form-item label="所属角色" name="roleIds">
        <a-tree-select
          v-model:value="form.roleIds"
          :tree-data="roleList"
          tree-checkable
          class="formInput"
          allow-clear
          :field-names="{
            label: 'name',
            value: 'id',
            children: 'childRoleList',
          }"
          :show-checked-strategy="SHOW_PARENT"
          placeholder="请选择"
          tree-node-filter-prop="label"
          @change="changeRole"
        />
      </a-form-item>

      <a-form-item label="电站权限" name="stationPermiType">
        <a-select v-model:value="form.stationPermiType" class="formInput">
          <a-select-option :value="1">所有</a-select-option>
          <a-select-option :value="2">仅本企业关联电站</a-select-option>
          <a-select-option :value="3">自定义</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="电站名称"
        name="station"
        v-if="form.stationPermiType === 3"
      >
        <a-select
          v-model:value="form.station"
          class="formInput"
          placeholder="请选择"
          mode="multiple"
        >
          <a-select-option
            v-for="item in stationtList"
            :value="item.stationId"
            :key="item.stationId"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>


const $api = inject("$api");
const props = defineProps({
  addChildUserVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
});
const loading = ref(false);
const resetLoading = ref(false);
const visible = ref(props.addChildUserVisible);
const emits = defineEmits(["update:addChildUserVisible", "handleSaveChildCB"]);
watch(
  () => props.addChildUserVisible,
  (val) => {
    visible.value = val;
    if (val) {
      getRoleList();
      // getUserListById();
      getCompanyStationtList();
    }
  }
);
const labelCol = { style: { width: "100px" } };
const formRef = ref(null);
const form = ref({
  account: null,
  username: null,
  password: null,
  roleIds: undefined,
  stationPermiType: 2,
  station: undefined,
});
const validatePass = async (_rule, value) => {
  if (value === undefined) {
    return Promise.reject("请确认密码");
  } else if (value !== form.value.password) {
    return Promise.reject("两次密码输入不匹配");
  } else {
    return Promise.resolve();
  }
};
const rules = ref({
  account: [
    {
      required: true,
      message: "请输入账号",
    },
  ],
  username: [
    {
      required: true,
      message: "请输入账号名",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
    },
  ],
  checkPassWord: [{ validator: validatePass, trigger: "change" }],
  roleIds: [
    {
      required: true,
      message: "请选择所属角色",
    },
  ],
  stationPermiType: [
    {
      required: true,
      message: "请选择电站权限",
    },
  ],
  station: [
    {
      required: true,
      message: "请选择电站",
    },
  ],
});

const cancel = () => {
  emits("update:addChildUserVisible", false);
  form.value = {
    account: null,
    username: null,
    password: null,
    roleIds: undefined,
    stationPermiType: 2,
    station: undefined,
  };
  formRef.value.clearValidate();
};
const roleSelectedOptions = ref([]);
const changeRole = (val) => {
  roleSelectedOptions.value = val;
};
const roleList = ref([]);
const getRoleList = async () => {
  const res = await $api.roleList({
    roleType: 1, // 1 企业角色 2 内部角色组 3 内部子角色
  });
  if (res.code === 0) {
    roleList.value = res.data;
  }
};
const getUserListById = async () => {
  const params = {
    companyId: props.rowData.id,
    id: props.rowData.masterAccountId,
  };
  const res = await $api.userListById(params);
  if (res.code === 0) {
    const userData = res.data[0];
    form.value = {
      masterAccount: userData.account || null,
      masterAccountEnable: userData.enable || 1,
      roleIds: userData.roleIds || undefined,
      stationPermiType: userData.stationPermiType || 2,
    };
  }
};
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const params = {
        ...form.value,
        userType: 3, // 1：内部用户 2：企业主账号 3：企业子账号
        companyId: props.rowData.id,
        roleIds: roleSelectedOptions.value,
      };
      loading.value = true;
      const res = await $api.userAdd(params);
      loading.value = false;
      if (res.code === 0) {
        message.success("新增成功");
        cancel();
        emits("handleSaveChildCB");
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const stationtList = ref([]);
const getCompanyStationtList = async () => {
  const res = await $api.companyStationtList();
  if (res.code === 0) {
    stationtList.value = res.data;
  }
};
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 300px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.areaSelectContent {
  display: inline-block;
}
.areaSelectContent {
  display: inline-block;
}
.areaSelect {
  display: inline-block;
  width: 113px;
  margin-right: 5px;
  &:last-child {
    margin-right: 0;
  }
}
</style>